package com.sgy.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author shenguangyang
 * @date 2022-08-14 8:00
 */
public class SqliteUtils {
    private static final Logger log = LoggerFactory.getLogger(SqliteUtils.class);
    /**
     * 字符常量：斜杠 {@code '/'}
     */
    public static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    public static final char BACKSLASH = '\\';

    private static final Logger logger = LoggerFactory.getLogger(SqliteUtils.class);

    /**
     * 初始化项目db
     */
    public static void initProjectDb(Connection connection, String dbName) {
        //判断数据表是否存在
        boolean hasPro = false;
        try {
            hasPro = true;
            // 测试数据表是否存在
            connection.prepareStatement(String.format("select * from %s", dbName)).execute();
        } catch (SQLException e) {
            // 不存在
            logger.debug("table {} is not exist", dbName);
            hasPro = false;
        }
        // 不存在时创建db
        if (!hasPro) {
            logger.debug("start init {} db", dbName);
            InputStream is = null;
            try {
                // 读取初始化数据sql
                is = ResourceUtil.getStream("classpath:sql/init.sql");
            } catch (Exception e) {
                e.printStackTrace();
            }

            //获取sql
            String sql = "";
            InputStreamReader isr = null;
            try {
                assert is != null;
                isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader bf = new BufferedReader(isr);
                String content = "";
                StringBuilder sb = new StringBuilder();
                while (true) {
                    content = bf.readLine();
                    if (content == null) {
                        break;
                    }
                    sb.append(content.trim()).append("\n");
                }
                sql = sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert isr != null;
                    isr.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                // 开始初始化数据库
                connection.setAutoCommit(false);
                connection.prepareStatement(sql).execute();
                //提交sql
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            logger.debug("finish init {} db", dbName);
        } else {
            logger.debug("{} db is exist", dbName);
        }
    }

    public static void initDb(Connection connection, String... sqls) {
        try {
            for (String str : sqls) {
                connection.setAutoCommit(false);
                connection.prepareStatement(str).execute();
            }
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        logger.debug("finish initDb");
    }

    public static void initSqliteFile(String filePath) {
        log.info("init sqlite file: {}", filePath);
        File file = new File(filePath);

        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFilePath(String url) {
        url = url.replace("jdbc:sqlite:", "");
        return url;
    }

    public static String getDbName(String url) {
        String filePath = getFilePath(url);
        return getName(filePath);
    }

    /**
     * 返回文件名
     *
     * @param filePath 文件
     * @return 文件名
     */
    public static String getName(String filePath) {
        if (null == filePath) {
            return null;
        }
        int len = filePath.length();
        if (0 == len) {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1))) {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--) {
            c = filePath.charAt(i);
            if (isFileSeparator(c)) {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    /**
     * 是否为Windows或者Linux（Unix）文件分隔符<br>
     * Windows平台下分隔符为\，Linux（Unix）为/
     *
     * @param c 字符
     * @return 是否为Windows或者Linux（Unix）文件分隔符
     */
    public static boolean isFileSeparator(char c) {
        return SLASH == c || BACKSLASH == c;
    }
}
